<template>
  <div class="weekly-container">
    <div class="weekly-header">
      <h3>周报填写</h3>
      <el-button type="primary" @click="submitWeekly" :loading="submitting">提交周报</el-button>
    </div>

    <el-card class="weekly-form-card">
      <template #header>
        <div class="card-header">
          <span>{{ currentWeek }}</span>
          <el-tag type="primary">{{ getWeekRange() }}</el-tag>
        </div>
      </template>

      <el-form ref="weeklyFormRef" :model="weeklyForm" :rules="rules" label-width="120px">
        <el-form-item label="本周工作总结" prop="summary">
          <el-input
            v-model="weeklyForm.summary"
            type="textarea"
            :rows="4"
            placeholder="请总结本周主要工作和完成情况"
          />
        </el-form-item>

        <el-divider content-position="center">工作明细</el-divider>
        
        <draggable v-model="weeklyForm.projects" item-key="id" handle=".project-label-drag" 
                  animation="300" ghostClass="ghost" chosenClass="ghost">
          <template #item="{ element: project, index }">
            <div :id="`project-${index}`">
              <div style="border-top: 1px solid rgb(220 223 230);"></div>
              <el-row :gutter="20">
                <el-col :xs="24" :sm="24" :md="24">
                  <el-form-item :prop="`projects[${index}].projectId`"
                                :rules="rules.projectId">
                    <template #label>
                      <div class="project-label-drag">
                        {{ index+1 }} 、
                      </div>
                    </template>
                    <el-select v-model="project.projectId" placeholder="请选择项目名称" size="large"
                              style="width:calc(90% - 70px);margin-right: 20px" 
                              @change="handleProjectChange(project, project.projectId)" filterable>
                      <el-option v-for="item in projectOptions" :key="item.value" :label="item.label"
                                :value="item.value" :disabled="isProjectSelected(item.value)" />
                    </el-select>
                    <el-button type="danger" @click="deleteProject(index)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                    <el-button type="primary" plain @click="addTask(index)">
                      <el-icon><Plus /></el-icon>
                    </el-button>
                  </el-form-item>
                </el-col>
              </el-row>
              
              <draggable v-model="project.tasks" item-key="id" handle=".label-drag"
                        @change="updateTaskSort(index)" animation="300"
                        ghostClass="ghost" chosenClass="ghost">
                <template #item="{ element: task, index: taskIndex }">
                  <div :id="`task-${index}-${taskIndex}`" style="margin-left: 20px;">
                    <el-row :gutter="20">
                      <el-col :xs="24" :sm="24" :md="24">
                        <el-form-item 
                          :prop="`projects[${index}].tasks[${taskIndex}].content`"
                          :rules="rules.taskContent">
                          <template #label>
                            <div class="label-drag">
                              （{{ `${taskIndex + 1}`}}）
                            </div>
                          </template>
                          <el-input maxlength="999" @change="inputChange"
                                  style="width: calc(90% - 70px);margin-right: 20px;"
                                  placeholder="请输入任务内容" v-model="task.content"
                                  type="textarea"
                                  :autosize="{ minRows: 2, maxRows: 4 }"></el-input>
                          <el-button type="danger" plain @click="deleteTask(index, taskIndex)">
                            <el-icon><Minus /></el-icon>
                          </el-button>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </div>
                </template>
              </draggable>
            </div>
          </template>
        </draggable>
        
        <div class="add-project">
          <el-button type="primary" plain @click="addProject">
            <el-icon><Plus /></el-icon> 添加项目
          </el-button>
        </div>

        <el-divider />

        <el-form-item label="下周工作计划" prop="nextWeekPlan">
          <el-input
            v-model="weeklyForm.nextWeekPlan"
            type="textarea"
            :rows="4"
            placeholder="请填写下周工作计划"
          />
        </el-form-item>

        <el-form-item label="问题与建议">
          <el-input
            v-model="weeklyForm.issues"
            type="textarea"
            :rows="3"
            placeholder="可选，填写本周遇到的问题及建议"
          />
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Delete, Plus, Minus } from '@element-plus/icons-vue'
import draggable from 'vuedraggable'

const weeklyFormRef = ref(null)
const currentWeek = ref(`${new Date().getFullYear()}年第${getWeekNumber(new Date())}周`)
const submitting = ref(false)

// 项目选项
const projectOptions = ref([
  { value: 'p1', label: '官网重构项目' },
  { value: 'p2', label: '移动端适配' },
  { value: 'p3', label: '数据分析平台' },
  { value: 'p4', label: '微信小程序开发' },
  { value: 'p5', label: '内部管理系统' }
])

const weeklyForm = reactive({
  summary: '',
  projects: [
    {
      id: Date.now(),
      projectId: '',
      projectName: '',
      tasks: [
        {
          id: Date.now() + 1,
          content: '',
          sort: 1
        }
      ]
    }
  ],
  nextWeekPlan: '',
  issues: ''
})

const rules = reactive({
  summary: [
    { required: true, message: '请填写本周工作总结', trigger: 'blur' }
  ],
  projectId: [
    { required: true, message: '请选择项目', trigger: 'change' }
  ],
  taskContent: [
    { required: true, message: '请输入任务内容', trigger: 'blur' }
  ],
  nextWeekPlan: [
    { required: true, message: '请填写下周工作计划', trigger: 'blur' }
  ]
})

function getWeekNumber(date) {
  const firstDayOfYear = new Date(date.getFullYear(), 0, 1)
  const pastDaysOfYear = (date - firstDayOfYear) / 86400000
  return Math.ceil((pastDaysOfYear + firstDayOfYear.getDay() + 1) / 7)
}

function getWeekRange() {
  const now = new Date()
  const dayOfWeek = now.getDay() || 7 // 将周日的0转换为7
  
  // 计算本周的第一天(周一)
  const monday = new Date(now)
  monday.setDate(now.getDate() - dayOfWeek + 1)
  
  // 计算本周的最后一天(周日)
  const sunday = new Date(now)
  sunday.setDate(now.getDate() + (7 - dayOfWeek))
  
  return `${monday.getMonth() + 1}月${monday.getDate()}日 - ${sunday.getMonth() + 1}月${sunday.getDate()}日`
}

function addProject() {
  weeklyForm.projects.push({
    id: Date.now(),
    projectId: '',
    projectName: '',
    tasks: [
      {
        id: Date.now() + 1,
        content: '',
        sort: 1
      }
    ]
  })
}

function deleteProject(index) {
  if (weeklyForm.projects.length <= 1) {
    ElMessage.warning('至少保留一个项目')
    return
  }
  weeklyForm.projects.splice(index, 1)
}

function addTask(projectIndex) {
  const tasks = weeklyForm.projects[projectIndex].tasks
  tasks.push({
    id: Date.now(),
    content: '',
    sort: tasks.length + 1
  })
}

function deleteTask(projectIndex, taskIndex) {
  const tasks = weeklyForm.projects[projectIndex].tasks
  if (tasks.length <= 1) {
    ElMessage.warning('至少保留一个任务')
    return
  }
  tasks.splice(taskIndex, 1)
  // 更新排序
  updateTaskSort(projectIndex)
}

function updateTaskSort(projectIndex) {
  const tasks = weeklyForm.projects[projectIndex].tasks
  tasks.forEach((task, index) => {
    task.sort = index + 1
  })
}

function handleProjectChange(project, projectId) {
  const selectedProject = projectOptions.value.find(p => p.value === projectId)
  if (selectedProject) {
    project.projectName = selectedProject.label
  }
}

function isProjectSelected(projectId) {
  return weeklyForm.projects.some(p => p.projectId === projectId && p.projectId !== '')
}

function inputChange() {
  console.log('内容更新')
}

function submitWeekly() {
  weeklyFormRef.value.validate((valid) => {
    if (!valid) {
      ElMessage.warning('请完善表单信息')
      return
    }
    
    submitting.value = true
    
    // 模拟提交
    setTimeout(() => {
      submitting.value = false
      ElMessage.success('周报提交成功')
      
      // 重置表单
      weeklyForm.summary = ''
      weeklyForm.projects = [
        {
          id: Date.now(),
          projectId: '',
          projectName: '',
          tasks: [
            {
              id: Date.now() + 1,
              content: '',
              sort: 1
            }
          ]
        }
      ]
      weeklyForm.nextWeekPlan = ''
      weeklyForm.issues = ''
    }, 1500)
  })
}
</script>

<style scoped>
.weekly-container {
  padding: 20px;
  background-color: #f9fbff;
  min-height: 100%;
}

.weekly-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.weekly-header h3 {
  color: #1e5eff;
  font-size: 1.5rem;
}

.weekly-form-card {
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.project-label-drag {
  cursor: move;
  padding: 2px 4px;
  border-radius: 4px;
}

.project-label-drag:hover {
  background-color: #e6f1ff;
}

.label-drag {
  cursor: move;
  padding: 2px 4px;
  border-radius: 4px;
}

.label-drag:hover {
  background-color: #e6f1ff;
}

.add-project {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

:deep(.el-form-item__label) {
  color: #606266;
  font-weight: 600;
}

:deep(.el-divider__text) {
  background-color: #f9fbff;
  color: #909399;
}

:deep(.el-button--primary) {
  background-color: #1e5eff;
}

:deep(.el-tag--primary) {
  background-color: #e6f1ff;
  border-color: #1e5eff;
  color: #1e5eff;
}

:deep(.el-divider) {
  margin: 15px 0;
}

.ghost {
  opacity: 0.5;
  background: #c8ebfb;
}

@media screen and (max-width: 768px) {
  .task-action {
    margin-top: -20px;
    margin-bottom: 10px;
    justify-content: flex-end;
  }
}
</style> 